package cn.lsg.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import java.io.Writer;
import java.net.SocketException;
import java.util.Properties;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.net.smtp.AuthenticatingSMTPClient;
import org.apache.commons.net.smtp.SMTPReply;
import org.apache.commons.net.smtp.SimpleSMTPHeader;
import org.apache.log4j.Logger;

/**
 * 邮件发送工具类
 * 
 */
public class UtilEmail {
	private static final Logger log = Logger.getLogger(UtilEmail.class);

	private static String Email_Host, Email_UserName, encode = "utf-8",
			Email_Password, Email_Form;
	// 配置文件
	private static Properties prop;

	static {// default email configure
		File file = new File(UtilEmail.class.getResource("/").getPath()
				+ "/email.properties");
		if (file.isFile()) {
			prop = new Properties();
			try {
				prop.load(new FileInputStream(file));
				Email_Host = prop.getProperty("Email_Host");
				Email_UserName = prop.getProperty("Email_UserName");
				Email_Password = prop.getProperty("Email_Password");
				Email_Form = prop.getProperty("Email_Form");
			} catch (IOException e) {
				log.error("Email配置文件夹读取错误", e);
			}
		} else {
			log.warn("Email配置文件找不到:" + file.getPath());
		}
	}

	/**
	 * 邮件发送
	 * 
	 * @param host
	 *            主机
	 * @param userName
	 *            用户名
	 * @param encode
	 *            内容编码
	 * @param password
	 *            密码
	 * @param sender
	 *            发送人
	 * @param recipient
	 *            收件人
	 * @param subject
	 *            主题
	 * @param msg
	 *            信息
	 * @throws Exception
	 **/
	public synchronized final static void send(String host, String userName,
			String password, String sender, String encode, String recipient,
			String subject, String msg) throws Exception {

		AuthenticatingSMTPClient client = new AuthenticatingSMTPClient();

		SimpleSMTPHeader header = new SimpleSMTPHeader(sender, recipient,
				subjectEncode(subject, encode));
		header.addHeaderField("Mime-Version", "1.0");
		header.addHeaderField("Content-Transfer-Encoding", "base64");
		header.addHeaderField("Content-Type", "text/html;Charset=\"" + encode
				+ "\"");
		client.connect(host);

		if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) {
			client.disconnect();
			throw new SocketException("SMTP 服务器拒绝连接");
		}

		client.ehlo(host);
		client.auth(AuthenticatingSMTPClient.AUTH_METHOD.LOGIN, userName,
				password);
		client.setSender(sender);
		client.addRecipient(recipient);

		Writer writer = client.sendMessageData();
		if (writer != null) {
			writer.write(header.toString());
			writer.write(base64(msg));
			writer.close();
			client.completePendingCommand();
		}

		client.logout();
		client.disconnect();
	}

	public synchronized final static void send(String recipient,
			String subject, String msg) throws Exception {
		try {
			send(Email_Host, Email_UserName, Email_Password, Email_Form,
					encode, recipient, subject, msg);
		} catch (Exception e) {
			throw e;
		}
	}

	/**
	 * 邮件主题base64编码
	 * 
	 * @param str
	 * @param encode
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private synchronized final static String subjectEncode(String str,
			String encode) throws UnsupportedEncodingException {
		return ("=?" + encode + "?B?" + base64(str) + "?=");
	}

	/**
	 * base64 编码
	 * 
	 * @param str
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private synchronized final static String base64(String str)
			throws UnsupportedEncodingException {
		return (new String(Base64.encodeBase64(str.getBytes("UTF-8")), "UTF-8"));
	}

}
